#include "iniconfig.h"
#include <iniparser/iniparser.h>
#include <iniparser/dictionary.h>

IniConfig::IniConfig():_isloaded(false){

}
IniConfig::~IniConfig(){

}

bool IniConfig::loadfile(const std::string &filepath){
    dictionary *ini = NULL;
    ini = iniparser_load(filepath.c_str());
    if(!ini){
        fprintf(stderr, "cannot parse file: %s\n", filepath.c_str());
        return false;
    }
    
    const char *ip = iniparser_getstring(ini, "database:ip", "127.0.0.1");
    const unsigned short db_port = iniparser_getint(ini, "database:port", 3306);
    const char *db_user = iniparser_getstring(ini, "database:user", "root");
    const char *db_pwd = iniparser_getstring(ini, "database:pwd", "181278");
    const char *db_name = iniparser_getstring(ini, "database:db", "sharebike");

    const unsigned short server_port = iniparser_getint(ini, "server:port", 9090);

    const unsigned short read_tv_sec = iniparser_getint(ini, "timeout:read_tv_sec", 10);
    const unsigned short read_tv_usec = iniparser_getint(ini, "timeout:read_tv_usec", 0);
    const unsigned short write_tv_sec = iniparser_getint(ini, "timeout:write_tv_sec", 10);
    const unsigned short write_tv_usec = iniparser_getint(ini, "timeout:write_tv_usec", 0);

    const unsigned short max_conn = iniparser_getint(ini, "databse:max_conns", 30);
    const unsigned short min_conn = iniparser_getint(ini, "database:min_conns", 10);
    const unsigned short conn_timeout = iniparser_getint(ini, "database:conn_timeout", 5); 
    const unsigned short conn_free_time = iniparser_getint(ini, "database:max_free_time", 60);

    this->_config = st_env_config(std::string(ip), db_port, std::string(db_user), \
                                  std::string(db_pwd), std::string(db_name), server_port, \
                                read_tv_sec, read_tv_usec, write_tv_sec, write_tv_usec, \
                                max_conn, min_conn, conn_timeout, conn_free_time);
    iniparser_freedict(ini);
    _isloaded = true;
    return _isloaded;
}

_st_env_config &IniConfig::getconfig(){
    return this->_config;
}
